import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:nft_shop/box/page/details/box_details_page.dart';
import 'package:nft_shop/box/page/details/split_box_page.dart';
import 'package:nft_shop/market/page/details/works_3d_details_page.dart';
import 'package:nft_shop/market/page/details/works_details_page.dart';
import 'package:nft_shop/my/conteroller/my_write_conteroller.dart';
import 'package:nft_shop/my/model/models.dart';
import 'package:nft_shop/my/page/order/my_resell_page.dart';
import 'package:nft_shop/my/page/set/check_work_page.dart';
import 'package:nft_shop/my/page/set/my_royalties_record_page.dart';
import 'package:nft_shop/my/view/album_hint.dart';
import 'package:nft_shop/my/view/my_check_work_widget.dart';
import 'package:nft_shop/my/view/my_editor_works_bottom.dart';
import 'package:nft_shop/my/view/my_new_album_widget.dart';
import 'package:nft_shop/net/dio_api.dart';
import 'package:nft_shop/net/service_repository.dart';
import 'package:nft_shop/res/constant.dart';
import 'package:nft_shop/res/global.dart';
import 'package:nft_shop/util/image_util.dart';
import 'package:nft_shop/util/other_utils.dart';
import 'package:nft_shop/util/route_observer.dart';
import 'package:nft_shop/widgets/load_image.dart';
import 'package:nft_shop/widgets/status_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'my_works_creation_page.dart';

class MyWriteListTypePage extends StatefulWidget {
  int? section;
  int? row;

  MyWriteListTypePage({Key? key, this.section, this.row}) : super(key: key);

  @override
  _MyWriteListTypePageState createState() => _MyWriteListTypePageState();
}

class _MyWriteListTypePageState extends State<MyWriteListTypePage>
    with AutomaticKeepAliveClientMixin, RouteAware {
  /// 分页第一页页码
  static const int pageNumFirst = 1;

  /// 当前第几页
  int currentPageNum = pageNumFirst;

  /// 分页条目数量
  int pageSize = 20;

  /// 页面数据
  List list = [];

  ///状态
  int _status = LoadStatusType.loading;

  ///刷新组件
  RefreshController refreshController =
      RefreshController(initialRefresh: false);

  int get status => _status;

  set status(int value) {
   try{
     _status = value;
     setState(() {});
   }catch(e){}
  }

  @override
  bool get wantKeepAlive => true;

  //获取数据
  Future loadData({int? pageNum}) async {
    return await ServiceRepository.mySpecialList(
        page: pageNum,
        pageSize: pageSize,
        smallType: widget.row!,
        bigType: widget.section!);

    if (MyWriteConteroller.to.rowIndex == widget.row &&
        MyWriteConteroller.to.sectionIndex == widget.section) {
      print("请求参数----${widget.section!}--${widget.row!}");
      return await ServiceRepository.mySpecialList(
          page: pageNum!,
          pageSize: pageSize,
          smallType: widget.row!,
          bigType: widget.section!);
    } else {
      return [];
    }
  }

  /// 下拉刷新
  ///
  /// [init] 是否是第一次加载
  /// true:  Error时,需要跳转页面
  /// false: Error时,不需要跳转页面,直接给出提示
  Future<List?> refresh({bool init = false}) async {
    try {
      currentPageNum = pageNumFirst;
      MyGoodsSpecialDataModel model = await loadData(pageNum: pageNumFirst);
      MyWriteConteroller.to.zhuzaoy = model.zhuzaoy ?? "0";
      MyWriteConteroller.to.zhuzaon = model.zhuzaon ?? "0";
      if (model.data!.isEmpty) {
        refreshController.refreshCompleted(resetFooterState: true);
        list.clear();
        status = LoadStatusType.empty;
      } else {
        list.clear();
        list.addAll(model.data!);
        refreshController.refreshCompleted();
        // 小于分页的数量,禁止上拉加载更多
        if (model.data!.length < pageSize) {
          refreshController.loadNoData();
        } else {
          //防止上次上拉加载更多失败,需要重置状态
          refreshController.loadComplete();
        }
        status = LoadStatusType.success;
      }
      return model.data!;
    } catch (e, s) {
      /// 页面已经加载了数据,如果刷新报错,不应该直接跳转错误页面
      /// 而是显示之前的页面数据.给出错误提示
      if (init) list.clear();
      refreshController.refreshFailed();
      status = LoadStatusType.empty;
      // setError(e, s);
      return null;
    }
  }

  /// 上拉加载更多
  Future<List?> loadMore() async {
    try {
      MyGoodsSpecialDataModel model = await loadData(pageNum: currentPageNum);
      MyWriteConteroller.to.zhuzaoy = model.zhuzaoy ?? "0";
      MyWriteConteroller.to.zhuzaon = model.zhuzaon ?? "0";
      if (model.data!.isEmpty) {
        currentPageNum--;
        refreshController.loadNoData();
      } else {
        list.addAll(model.data!);
        if (model.data!.length < pageSize) {
          refreshController.loadNoData();
        } else {
          refreshController.loadComplete();
        }
        setState(() {});
      }
      return model.data!;
    } catch (e, s) {
      currentPageNum--;
      refreshController.loadFailed();
      return null;
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    RouteUtils.routeObserver
        .subscribe(this, ModalRoute.of(context) as PageRoute);
  }

  //回到当前页面
  @override
  void didPopNext() {
    print("我的界面--刷新数据---");
    refresh();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    refresh();
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: refreshController,
      header: WaterDropHeader(),
      footer: ClassicFooter(
        noDataText: "",
      ),
      onRefresh: refresh,
      onLoading: loadMore,
      enablePullUp: true,
      child: _gridViewWidget(),
    );
  }

  ///我的
  Widget _gridViewWidget() {
    if (status != LoadStatusType.success) {
      return StatusViews(status);
    }

    return GridView.builder(
        shrinkWrap: true,
        padding: EdgeInsets.only(
          top: 10,
        ),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          crossAxisSpacing: 15,
          mainAxisSpacing: 15,
          childAspectRatio: 167 / 230,
        ),
        itemCount: list.length,
        itemBuilder: (context, index) {
          MyGoodsSpecialModel model = list[index];
          if (model.type == 3) {
            //专辑
            return _itemAlbumWidget(model);
          } else {
            return _itemWidget(model);
          }
        });
  }

  ///item
  Widget _itemWidget(MyGoodsSpecialModel model) {
    double itemWidth = (Get.width - 45) / 2;
    double itemHeight = itemWidth * 173 / 167;
    String showType = "";
    if (model.specialCastStatus == 1) {
      showType = "未铸造";
    } else if (model.specialCastStatus == 2) {
      showType = "铸造中";
    } else if (model.specialCastStatus == 3) {
      showType = "已铸造";
    }

    return InkWell(
      onTap: () {
        //已铸造
        if (widget.section == 1) {
          //1整体藏品 2整体盲盒 3专辑
          if (model.type == 1) {
            print("请求参数---${model.specialId!}");
            // 2整体铸造详情  3整体详情
            //3D
            if (model.specialTypeId == 2) {
              Get.to(Works3DDetailsPage(
                  id: model.specialId!, type: 2, isHidePayment: true));
            } else {
              Get.to(WorksDetailsPage(
                  id: model.specialId!, type: 2, isHidePayment: true));
            }
          } else {
            //1单个藏品详情 2整体铸造详情  3整体详情
            if (ObjectUtil.isEmpty(model.goodsId)) {
              Get.to(BoxDetailsPage(
                  id: model.specialId!, type: 3, isHidePayment: true));
            } else {
              Get.to(BoxDetailsPage(
                  id: model.goodsId!, type: 3, isHidePayment: true));
            }
          }
        } else {
          //为铸造
          //1整体藏品 2整体盲盒 3专辑
          if (model.type == 1) {
            // 2整体铸造详情  3整体详情
            //3D
            if (model.specialTypeId == 2) {
              Get.to(Works3DDetailsPage(
                  id: model.specialId!, type: 2, isHidePayment: true));
            } else {
              Get.to(WorksDetailsPage(
                  id: model.specialId!, type: 2, isHidePayment: true));
            }
          } else {
            //1单个藏品详情 2整体铸造详情  3整体详情
            // Get.to(BoxDetailsPage(
            //     id: model.goodsId!, type: 2, isHidePayment: true));

            //1单个藏品详情 2整体铸造详情  3整体详情
            if (ObjectUtil.isEmpty(model.goodsId)) {
              Get.to(BoxDetailsPage(
                  id: model.specialId!, type: 2, isHidePayment: true));
            } else {
              Get.to(BoxDetailsPage(
                  id: model.goodsId!, type: 2, isHidePayment: true));
            }
          }
        }
      },
      child: Container(
        decoration: BoxDecoration(
            color: Global.kTheme.colorBackground1,
            borderRadius: BorderRadius.circular(10.0),
            boxShadow: [
              BoxShadow(
                  color: Color(0x80E6E6E6),
                  offset: Offset(2.0, 2.0), //阴影xy轴偏移量
                  blurRadius: 8.0, //阴影模糊程度
                  spreadRadius: 3.0 //阴影扩散程度
                  )
            ]),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Stack(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: LoadImage(
                    model.thumb ?? "",
                    width: double.infinity,
                    height: itemHeight,
                    fit: BoxFit.fitHeight,
                  ),
                ),
                Positioned(
                  left: 9,
                  top: 8,
                  child: _objectState(showType),
                ),
                Positioned(
                  bottom: 5,
                  left: 5,
                  child: _objectType(
                    model.specialTypeName ?? "",
                  ),
                ),
              ],
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 7),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          model.title ?? "",
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontFamily: Global.mySemiboldFont,
                              fontSize: 14,
                              color: Global.kTheme.textPrimary4),
                        ),
                        SizedBox(
                          height: 2,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            ClipRRect(
                              borderRadius: BorderRadius.circular(9),
                              child: LoadImage(
                                model.portrait ?? "header_img",
                                width: 18,
                                height: 18,
                                holderImg: "header_img",
                              ),
                            ),
                            SizedBox(
                              width: 4,
                            ),
                            Expanded(
                              child: Text(
                                model.nickname ?? "",
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: 12,
                                    color: Global.kTheme.textPrimary0,
                                    fontFamily: Global.mySemiboldFont),
                              ),
                            ),
                          ],
                        )
                      ],
                    ),
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Visibility(
                        //special_sell_status 转售状态 1是0否
                        visible: model.specialSellStatus == 1 ? false : true,
                        child: InkWell(
                          onTap: () {
                            botttomOperationView(model);
                          },
                          child: Container(
                            padding: EdgeInsets.symmetric(
                                horizontal: 10, vertical: 2),
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(4),
                                color: Global.kTheme.colorBackground3),
                            child: Text(
                              "操作",
                              style: TextStyle(
                                  fontSize: 12,
                                  color: Global.kTheme.textPrimary5,
                                  fontFamily: Global.mySemiboldFont),
                            ),
                          ),
                        ),
                      )
                    ],
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  //item
  Widget _itemAlbumWidget(MyGoodsSpecialModel model) {
    double itemWidth = (Get.width - 45) / 2;
    double itemHeight = itemWidth * 173 / 167;
    return InkWell(
      onTap: () {},
      child: Container(
        decoration: BoxDecoration(
            color: Global.kTheme.colorBackground1,
            borderRadius: BorderRadius.circular(10.0),
            boxShadow: [
              BoxShadow(
                  color: Color(0x80E6E6E6),
                  offset: Offset(2.0, 2.0), //阴影xy轴偏移量
                  blurRadius: 8.0, //阴影模糊程度
                  spreadRadius: 3.0 //阴影扩散程度
                  )
            ]),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ClipRRect(
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(10), topRight: Radius.circular(10)),
              child: LoadImage(
                model.thumb ?? "",
                fit: BoxFit.fitHeight,
                width: double.infinity,
                height: itemHeight,
              ),
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 6),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          model.title ?? "",
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontFamily: Global.mySemiboldFont,
                              fontSize: 14,
                              color: Global.kTheme.textPrimary4),
                        ),
                        SizedBox(
                          height: 2,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Text(
                              "版权金",
                              style: TextStyle(
                                  fontSize: 12,
                                  color: Global.kTheme.inputHint1,
                                  fontFamily: Global.mySemiboldFont),
                            ),
                            SizedBox(
                              width: 2,
                            ),
                            Text(
                              "${model.specialAlbumRate ?? "0"} %",
                              style: TextStyle(
                                  fontSize: 15,
                                  color: Global.kTheme.textPrimary0,
                                  fontFamily: Global.mySemiboldFont),
                            ),
                          ],
                        )
                      ],
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      print("点击了编辑----");
                      botttomOperationView(model);
                    },
                    child: Container(
                      padding:
                          EdgeInsets.symmetric(horizontal: 10, vertical: 1),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(4),
                          color: Global.kTheme.colorBackground3),
                      child: Text(
                        "编辑",
                        style: TextStyle(
                            fontSize: 12,
                            color: Global.kTheme.textPrimary5,
                            fontFamily: Global.mySemiboldFont),
                      ),
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  //弹出框
  void botttomOperationView(MyGoodsSpecialModel model) {
    //index 0我的拥有 1我的卖出 2我的创作 3售卖中
    //type类型 类型 1整体藏品 2整体盲盒 3专辑 4藏品 5盲盒未拆 6盲盒已拆
    //special_cast_status铸造状态 1未铸造 2铸造中 3已铸造
    //goods_status状态: 0待上架 1正在出售 2被买家锁定 3买家已支付 4.超时 5已取消
    //special_sell_status 转售状态 1是0否
    List<String> lisName = [];
    if (model.type == 3) {
      // lisName.add("编辑专辑");
      lisName.add("查看作品");
      lisName.add("版税记录");
    } else {
      //special_cast_status铸造状态 1未铸造 2铸造中 3已铸造
      if (model.specialCastStatus == 1) {
        // lisName.add("编辑作品");
        lisName.add("立即铸造");
        lisName.add("查看画作");
        lisName.add("保存图片");
      } else if (model.specialCastStatus == 3) {
        lisName.add("发布售卖");
        lisName.add("查看画作");
        lisName.add("保存图片");
      }
    }
    if (lisName.length == 0) return;
    showModalBottomSheet<void>(
        context: context,

        /// 禁止拖动关闭
        enableDrag: false,

        /// 使用true则高度不受16分之9的最高限制
        isScrollControlled: true,
        backgroundColor: Colors.transparent,
        builder: (_) {
          return MyEditorWorksBottom(
            listName: lisName,
            onTap: (index) async {
              if (lisName[index] == "拆盲盒") {
                print("goodid是--${model.goodsId}-${model.specialId}");
                Get.to(SplitBoxPage(
                  goodid: model.goodsId ?? "",
                  id: model.goodsId ?? "",
                  isSingle: true,
                ));
              } else if (lisName[index] == "上架转售") {
                try {
                  EasyLoading.show(status: "加载中");
                  MemberExtendModel extend =
                      await ServiceRepository.memberExtend();
                  EasyLoading.dismiss();
                  if (ObjectUtil.isEmpty(extend.alipayAccount)) {
                    print("执行操作");
                    Utils.showElasticDialog<void>(
                      context: context,
                      barrierDismissible: false,
                      builder: (BuildContext context) {
                        return CollectionDialog();
                      },
                    );
                  } else {
                    Get.to(MyResellPage(
                      model: model,
                      isBooking: true,
                    ));
                  }
                } catch (e, s) {}
              } else if (lisName[index] == "发布售卖") {
                try {
                  EasyLoading.show(status: "加载中");
                  MemberExtendModel extend =
                      await ServiceRepository.memberExtend();
                  EasyLoading.dismiss();
                  if (extend.alipayAccount!.length == 0) {
                    Utils.showElasticDialog<void>(
                      context: context,
                      barrierDismissible: false,
                      builder: (BuildContext context) {
                        return CollectionDialog();
                      },
                    );
                  } else {
                    Get.to(MyResellPage(
                      model: model,
                      isBooking: true,
                    ));
                  }
                } catch (e, s) {}
              } else if (lisName[index] == "查看画作") {
                Utils.showElasticDialog<void>(
                  context: context,
                  builder: (BuildContext context) {
                    return MyCheckWorkWidget(model.thumb!);
                  },
                );
              } else if (lisName[index] == "编辑作品") {
                //type类型 类型 1整体藏品
                Get.to(MyWorksCreationPage(
                  model: model,
                ));
              } else if (lisName[index] == "保存图片") {
                print("图片地址---${model.thumb!}");
                AppUtil.saveImage(model.thumb!);
              } else if (lisName[index] == "编辑专辑") {
                showModalBottomSheet<void>(
                    context: context,
                    backgroundColor: Colors.transparent,

                    /// 禁止拖动关闭
                    enableDrag: false,

                    /// 使用true则高度不受16分之9的最高限制
                    isScrollControlled: true,
                    builder: (_) => MyNewAlbumWidget(
                          album: AlbumListModel.fromJsonToGoods(model.toJson()),
                          onPressed: () {
                            refresh();
                          },
                        ));
              } else if (lisName[index] == "版税记录") {
                Get.to(MyRoyaltiesRecordPage(
                  id: model.specialAlbumId ?? "",
                ));
              } else if (lisName[index] == "查看作品") {
                Get.to(CheckWorkPage(
                  id: model.specialAlbumId ?? "",
                ));
              } else if (lisName[index] == "立即铸造") {
                //type类型 类型 1整体藏品 2整体盲盒 3专辑 4藏品 5盲盒未拆 6盲盒已拆
                if (model.type == 1) {
                  Get.to(WorksDetailsPage(id: model.specialId ?? "", type: 2));
                } else {
                  Get.to(BoxDetailsPage(id: model.specialId ?? "", type: 2));
                }
              } else if (lisName[index] == "下架转售") {
                EasyLoading.show(status: "加载中");
                try {
                  //type类型 类型 1整体藏品 2整体盲盒 3专辑 4藏品 5盲盒未拆 6盲盒已拆
                  if (model.type == 4 || model.type == 5 || model.type == 6) {
                    //单个盲盒/藏品下架
                    await ServiceRepository.goodsSoldOut(id: model.goodsId);
                  } else if (model.type == 1 || model.type == 2) {
                    await ServiceRepository.soldOut(id: model.specialId);
                  }
                  EasyLoading.showToast("下架成功");
                  refresh();
                } catch (e, s) {
                  EasyLoading.showToast(http.setError(e, s));
                }
              }
            },
          );
        });
  }

  ///藏品状态
  Widget _objectState(String state) {
    Color color = Color(0xFF50E3C2);
    return Container(
        height: 24,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12),
          color: Global.kTheme.colorBackground3.withAlpha(100),
        ),
        padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        child: Text(
          state,
          style: TextStyle(
              color: Global.kTheme.textPrimary5,
              fontSize: 12,
              fontFamily: Global.mySemiboldFont),
        ));
  }

  ///藏品类型
  Widget _objectType(String state) {
    return Container(
      height: 17,
      decoration: BoxDecoration(
        color: Global.kTheme.colorBackground3,
      ),
      padding: EdgeInsets.symmetric(horizontal: 5, vertical: 2),
      child: Text(
        state,
        style: TextStyle(
            color: Global.kTheme.textPrimary5,
            fontSize: 10,
            fontFamily: Global.mySemiboldFont),
      ),
    );
  }
}
